package com.insight.modules.system.controller;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.insight.modules.system.entity.*;
import com.insight.modules.system.service.*;
import com.yuanqiao.insight.acore.system.service.ISysDictService;
import com.yuanqiao.insight.common.util.common.LocalCacheUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import com.insight.modules.constant.CommonConstant;
import org.insight.modules.system.entity.*;
import org.insight.modules.system.service.*;
import com.insight.common.api.vo.Result;
import com.insight.common.aspect.annotation.AutoLog;
import com.insight.common.aspect.annotation.SynMenu;
import com.insight.common.constant.CommonConstant;
import com.insight.common.system.vo.DictModel;
import com.insight.common.system.vo.LoginUser;
import com.insight.common.util.MD5Util;
import com.insight.common.util.oConvertUtils;
import com.insight.modules.system.entity.*;
import com.insight.modules.system.model.SysPermissionTree;
import com.insight.modules.system.model.TreeModel;
import com.insight.modules.system.service.*;
import com.insight.modules.system.util.PermissionDataUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单权限表 前端控制器
 * </p>
 *
 * @Author scott
 * @since 2018-12-21
 */
@Slf4j
@RestController
@RequestMapping("/sys/permission")
public class SysPermissionController {

    @Autowired
    private ISysPermissionService sysPermissionService;

    @Autowired
    private ISysRolePermissionService sysRolePermissionService;

    @Autowired
    private ISysPermissionDataRuleService sysPermissionDataRuleService;

    @Autowired
    private ISysDepartPermissionService sysDepartPermissionService;

    @Autowired
    private ISysPlatformTypeService platformTypeService;
    @Autowired
    private ISysDictService sysDictService;
    @Autowired
    private ISysThreePowerMenuService sysThreePowerMenuService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Value("${jeecg.shiro.realm}")
    private String realm;
    private static final LocalCacheUtils cacheUtils = LocalCacheUtils.getInstance();

    /**
     * 加载数据节点
     *
     * @return
     */
    @AutoLog(value = "菜单管理-列表展示")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<List<SysPermissionTree>> list(SysPermission sysPermission) {
        long start = System.currentTimeMillis();
        Result<List<SysPermissionTree>> result = new Result<>();
        try {
            if (sysPermissionService == null) {
                result.setResult(new ArrayList<>());
                result.setSuccess(true);
                return result;
            }
            LambdaQueryWrapper<SysPermission> query = new LambdaQueryWrapper<SysPermission>();
            if (sysPermission != null && sysPermission.getPlatformType() != null) {
                query.eq(SysPermission::getPlatformType, sysPermission.getPlatformType());
            }
            query.eq(SysPermission::getDelFlag, CommonConstant.DEL_FLAG_0);
            query.orderByAsc(SysPermission::getSortNo);

            List<SysPermission> allList = new ArrayList<>();
            if (sysPermission != null && StringUtils.isNotEmpty(sysPermission.getName())) {
                query.like(SysPermission::getName, sysPermission.getName());

                List<SysPermission> list1 = sysPermissionService.list(query);
                if (list1 != null) {
                    allList.addAll(list1);

                    for (SysPermission sysPer : list1) {
                        if (oConvertUtils.isNotEmpty(sysPer.getParentId())) {
                            SysPermission parentSysPer = sysPermissionService.queryByPerId(sysPer.getParentId());
                            if (parentSysPer != null) {
                                allList.add(parentSysPer);
                            }
                        }
                    }
                    Set<SysPermission> hashSet = new HashSet<>(allList);
                    allList = new ArrayList<>(hashSet);
                }
            } else {
                allList = sysPermissionService.list(query);
            }

            List<SysPermissionTree> treeList = new ArrayList<>();
            treeList = getMenuList(allList, true);
            setPlatformType(treeList);
            result.setResult(treeList);
            result.setSuccess(true);
            log.info("======获取全部菜单数据=====耗时:" + (System.currentTimeMillis() - start) + "毫秒");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }


    public void setPlatformType(List<SysPermissionTree> treeList) {
        Map<String, String> platformTypeMap = new HashMap<>();
        List<DictModel> platform_type_list = sysDictService.queryDictItemsByCode("platform_type");
        if (!CollectionUtils.isEmpty(platform_type_list)) {
            for (DictModel dictModel : platform_type_list) {
                platformTypeMap.put(dictModel.getValue(), dictModel.getText());
            }
            for (SysPermissionTree sysPermissionTree : treeList) {
                String text = platformTypeMap.get(sysPermissionTree.getPlatformType() + "");
                sysPermissionTree.setPlatformTypeText(text);
            }
        }
    }

    //获得树级结构菜单
    public List<SysPermissionTree> getMenuList(List<SysPermission> list, boolean isShowButton) {
        //拿到菜单的所有数据
        //存储根节点的菜单，即一级菜单
        List<SysPermissionTree> treeList = new ArrayList<>();
        //遍历所有数据，找到根节点菜单
        for (SysPermission permission : list) {
            SysPermissionTree tree = new SysPermissionTree(permission);
            if (StringUtils.isEmpty(tree.getParentId())) {
                //找到根节点菜单的时候，寻找这个根节点菜单下的子节点菜单。
                if (isShowButton) {
                    findChilds(tree, list);
                } else {
                    findChildsNotButton(tree, list);
                }

                //添加到根节点的列表中
                treeList.add(tree);
            }
        }
        return treeList;
    }

    private void findChildsNotButton(SysPermissionTree sysPermissionTree, List<SysPermission> list) {
        List<SysPermissionTree> childlist = new ArrayList<>();
        //遍历所有数据，找到是入参父节点的子节点的数据，然后加到childlist集合中。
        for (SysPermission permission : list) {
            SysPermissionTree tree = new SysPermissionTree(permission);
            if (sysPermissionTree.getId().equals(tree.getParentId()) && tree.getMenuType() != 2) {
                childlist.add(tree);
            }
        }
        //若子节点不存在，那么就不必再遍历子节点中的子节点了 直接返回。
        if (childlist.isEmpty())
            return;
        //设置父节点的子节点列表
        sysPermissionTree.setChildren(childlist);
        //若子节点存在，接着递归调用该方法，寻找子节点的子节点。
        for (SysPermissionTree childs : childlist) {
            if (childs.getMenuType() != 2) {
                findChildsNotButton(childs, list);
            }
        }

    }

    private void findChilds(SysPermissionTree root, List<SysPermission> list) {
        List<SysPermissionTree> childlist = new ArrayList<>();
        //遍历所有数据，找到是入参父节点的子节点的数据，然后加到childlist集合中。
        for (SysPermission permission : list) {
            SysPermissionTree tree = new SysPermissionTree(permission);
            if (root.getId().equals(tree.getParentId()))
                childlist.add(tree);
        }
        //若子节点不存在，那么就不必再遍历子节点中的子节点了 直接返回。
        if (childlist.size() == 0)
            return;
        //设置父节点的子节点列表
        root.setChildren(childlist);
        //若子节点存在，接着递归调用该方法，寻找子节点的子节点。
        for (SysPermissionTree childs : childlist) {
            findChilds(childs, list);
        }
    }
    /*update_begin author:wuxianquan date:20190908 for:先查询一级菜单，当用户点击展开菜单时加载子菜单 */

    /**
     * 系统菜单列表(一级菜单)
     *
     * @return
     */
    @RequestMapping(value = "/getSystemMenuList", method = RequestMethod.GET)
    public Result<List<SysPermissionTree>> getSystemMenuList() {
        long start = System.currentTimeMillis();
        Result<List<SysPermissionTree>> result = new Result<>();
        try {
            if (sysPermissionService == null) {
                result.setResult(new ArrayList<>());
                result.setSuccess(true);
                return result;
            }
            LambdaQueryWrapper<SysPermission> query = new LambdaQueryWrapper<SysPermission>();
            query.eq(SysPermission::getMenuType, CommonConstant.MENU_TYPE_0);
            query.eq(SysPermission::getDelFlag, CommonConstant.DEL_FLAG_0);
            query.orderByAsc(SysPermission::getSortNo);
            List<SysPermission> list = sysPermissionService.list(query);
            List<SysPermissionTree> sysPermissionTreeList = new ArrayList<SysPermissionTree>();
            if (list != null) {
                for (SysPermission sysPermission : list) {
                    if (sysPermission != null) {
                        SysPermissionTree sysPermissionTree = new SysPermissionTree(sysPermission);
                        sysPermissionTreeList.add(sysPermissionTree);
                    }
                }
            }
            result.setResult(sysPermissionTreeList);
            result.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        log.info("======获取一级菜单数据=====耗时:" + (System.currentTimeMillis() - start) + "毫秒");
        return result;
    }

    /**
     * 查询子菜单
     *
     * @param parentId
     * @return
     */
    @RequestMapping(value = "/getSystemSubmenu", method = RequestMethod.GET)
    public Result<List<SysPermissionTree>> getSystemSubmenu(@RequestParam("parentId") String parentId) {
        Result<List<SysPermissionTree>> result = new Result<>();
        try {
            if (sysPermissionService == null || parentId == null) {
                result.setResult(new ArrayList<>());
                result.setSuccess(true);
                return result;
            }
            LambdaQueryWrapper<SysPermission> query = new LambdaQueryWrapper<SysPermission>();
            query.eq(SysPermission::getParentId, parentId);
            query.eq(SysPermission::getDelFlag, CommonConstant.DEL_FLAG_0);
            query.orderByAsc(SysPermission::getSortNo);
            List<SysPermission> list = sysPermissionService.list(query);
            List<SysPermissionTree> sysPermissionTreeList = new ArrayList<SysPermissionTree>();
            if (list != null) {
                for (SysPermission sysPermission : list) {
                    if (sysPermission != null) {
                        SysPermissionTree sysPermissionTree = new SysPermissionTree(sysPermission);
                        sysPermissionTreeList.add(sysPermissionTree);
                    }
                }
            }
            result.setResult(sysPermissionTreeList);
            result.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }
    /*update_end author:wuxianquan date:20190908 for:先查询一级菜单，当用户点击展开菜单时加载子菜单 */

    // update_begin author:sunjianlei date:20200108 for: 新增批量根据父ID查询子级菜单的接口 -------------

    /**
     * 查询子菜单
     *
     * @param parentIds 父ID（多个采用半角逗号分割）
     * @return 返回 key-value 的 Map
     */
    @GetMapping("/getSystemSubmenuBatch")
    public Result getSystemSubmenuBatch(@RequestParam("parentIds") String parentIds) {
        try {
            if (sysPermissionService == null || parentIds == null) {
                return Result.ok(new HashMap<>());
            }
            LambdaQueryWrapper<SysPermission> query = new LambdaQueryWrapper<>();
            List<String> parentIdList = Arrays.asList(parentIds.split(","));
            query.in(SysPermission::getParentId, parentIdList);
            query.eq(SysPermission::getDelFlag, CommonConstant.DEL_FLAG_0);
            query.orderByAsc(SysPermission::getSortNo);
            List<SysPermission> list = sysPermissionService.list(query);
            Map<String, List<SysPermissionTree>> listMap = new HashMap<>();
            if (list != null) {
                for (SysPermission item : list) {
                    if (item != null && item.getParentId() != null && parentIdList.contains(item.getParentId())) {
                        List<SysPermissionTree> mapList = listMap.get(item.getParentId());
                        if (mapList == null) {
                            mapList = new ArrayList<>();
                        }
                        mapList.add(new SysPermissionTree(item));
                        listMap.put(item.getParentId(), mapList);
                    }
                }
            }
            return Result.ok(listMap);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("批量查询子菜单失败：" + e.getMessage());
        }
    }
    // update_end author:sunjianlei date:20200108 for: 新增批量根据父ID查询子级菜单的接口 -------------

//	/**
//	 * 查询用户拥有的菜单权限和按钮权限（根据用户账号）
//	 *
//	 * @return
//	 */
//	@RequestMapping(value = "/queryByUser", method = RequestMethod.GET)
//	public Result<JSONArray> queryByUser(HttpServletRequest req) {
//		Result<JSONArray> result = new Result<>();
//		try {
//			String username = req.getParameter("username");
//			List<SysPermission> metaList = sysPermissionService.queryByUser(username);
//			JSONArray jsonArray = new JSONArray();
//			this.getPermissionJsonArray(jsonArray, metaList, null);
//			result.setResult(jsonArray);
//			result.success("查询成功");
//		} catch (Exception e) {
//			result.error500("查询失败:" + e.getMessage());
//			log.error(e.getMessage(), e);
//		}
//		return result;
//	}

    /**
     * @return
     */
    @RequestMapping(value = "/getUserPlatformTypeByToken", method = RequestMethod.GET)
    public Result<?> getUserPlatformTypeByToken(Boolean status) {
        Result<String> result = new Result<String>();
        //直接获取当前用户不适用前端token
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (oConvertUtils.isEmpty(loginUser)) {
            return Result.error("请登录系统！");
        }
        List<SysPermission> platformTypes = sysPermissionService.queryPlatformTypeByUser(loginUser.getId(), status);
        result.setResult(platformTypes.stream().filter(s -> s != null && !oConvertUtils.isEmpty(s.getPlatformType())).map(p -> String.valueOf(p.getPlatformType())).collect(Collectors.joining(",")));
        return result;
    }


    /**
     * 查询用户拥有的菜单权限和按钮权限
     *
     * @return
     */
    @RequestMapping(value = "/getUserPermissionByToken", method = RequestMethod.GET)
    public Result<?> getUserPermissionByToken(@RequestParam(name = "platformType", required = false) Integer platformType) {
        Result<JSONObject> result = new Result<JSONObject>();
        try {
            //直接获取当前用户不适用前端token
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            if (oConvertUtils.isEmpty(loginUser)) {
                return Result.error("请登录系统！");
            }
            List<SysPermission> metaList = new ArrayList<>();
            if (platformType != null) {
                metaList = sysPermissionService.queryByUserAndPlatformType(loginUser.getUsername(), platformType);
            } else {
                metaList = sysPermissionService.queryByUser(loginUser.getUsername());
            }
            int isThreePowers = Integer.parseInt((String) cacheUtils.getValueByKey(com.yuanqiao.insight.common.constant.CommonConstant.DATA_DICT_KEY + "insight_threePowers_isEnable"));
            if (isThreePowers == 1) {
                List<SysRole> roleList = sysRoleService.getInfoByUserId(loginUser.getId());
                if (CollUtil.isNotEmpty(roleList)) {
                    for (SysRole role : roleList) {
                        if (!CommonConstant.ADMIN.equals(role.getRoleCode())) {
                            List<SysThreePowerMenu> sysThreePowerMenus;
                            if (SysRoleController.getRoleAuditadm().contains(role.getRoleCode()) || SysRoleController.getRoleSecadm().contains(role.getRoleCode())) {
                                sysThreePowerMenus = sysRoleService.getSysThreepowerMenueByRoleCode(role.getRoleCode());
                                metaList = metaList.stream().filter(p -> sysThreePowerMenus.stream().anyMatch(tpm -> p.getId().equals(tpm.getPremissionId()))).collect(Collectors.toList());
                            } else if (SysRoleController.getRoleRoot().contains(role.getRoleCode())) {
                                // 如果开启了三员，是系统管理员
                                sysThreePowerMenus = sysThreePowerMenuService.list(new LambdaQueryWrapper<SysThreePowerMenu>()
                                        .ne(SysThreePowerMenu::getRoleCode, "other")
                                        .eq(SysThreePowerMenu::getShowType, "1"));
                                metaList = metaList.stream().filter(p -> sysThreePowerMenus.stream().noneMatch(tpm -> p.getId().equals(tpm.getPremissionId()))).collect(Collectors.toList());
                            } else {
                                // 如果开启了三员，是普通用户
                                sysThreePowerMenus = sysThreePowerMenuService.list(new LambdaQueryWrapper<SysThreePowerMenu>()
                                        .eq(SysThreePowerMenu::getShowType, "1"));
                                metaList = metaList.stream().filter(p -> sysThreePowerMenus.stream().noneMatch(tpm -> p.getId().equals(tpm.getPremissionId()))).collect(Collectors.toList());
                            }
                        }
                    }
                }
            }
            //添加首页路由
            //update-begin-author:taoyan date:20200211 for: TASK #3368 【路由缓存】首页的缓存设置有问题，需要根据后台的路由配置来实现是否缓存
//			if(!PermissionDataUtil.hasIndexPage(metaList)){
//				SysPermission indexMenu = sysPermissionService.list(new LambdaQueryWrapper<SysPermission>().eq(SysPermission::getName,"首页")).get(0);
//				metaList.add(0,indexMenu);
//			}
            //update-end-author:taoyan date:20200211 for: TASK #3368 【路由缓存】首页的缓存设置有问题，需要根据后台的路由配置来实现是否缓存
/**数据库已存在*/
//			if(platformType == 3){
//				//添加首页路由
//				PermissionDataUtil.addIndexPage(metaList);
//			}
            JSONObject json = new JSONObject();
            JSONArray menujsonArray = new JSONArray();
            this.getPermissionJsonArray(menujsonArray, metaList, null);
            JSONArray authjsonArray = new JSONArray();
            this.getAuthJsonArray(authjsonArray, metaList);
            //查询所有的权限
            LambdaQueryWrapper<SysPermission> query = new LambdaQueryWrapper<SysPermission>();
            query.eq(SysPermission::getDelFlag, CommonConstant.DEL_FLAG_0);
            query.eq(SysPermission::getMenuType, CommonConstant.MENU_TYPE_2);
            //query.eq(SysPermission::getStatus, "1");
            List<SysPermission> allAuthList = sysPermissionService.list(query);
            JSONArray allauthjsonArray = new JSONArray();
            this.getAllAuthJsonArray(allauthjsonArray, allAuthList);
            //路由菜单
            json.put("menu", menujsonArray);
            //按钮权限（用户拥有的权限集合）
            json.put("auth", authjsonArray);
            //全部权限配置集合（按钮权限，访问权限）
            json.put("allAuth", allauthjsonArray);
            result.setResult(json);
            result.success("查询成功");
        } catch (Exception e) {
            result.error500("查询失败:" + e.getMessage());
            log.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 查询用户拥有的菜单权限和按钮权限
     *
     * @return
     */
    @RequestMapping(value = "/getUserPermissionByTokenAndRole", method = RequestMethod.GET)
    public Result<?> getUserPermissionByTokenAndRole(@RequestParam(name = "platformType", required = false) Integer platformType,
                                                     @RequestParam(name = "roleCode", required = false) String roleCode) {
        Result<JSONObject> result = new Result<JSONObject>();
        try {
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            if (oConvertUtils.isEmpty(loginUser)) {
                return Result.error("请登录系统！");
            }
            List<SysPermission> metaList = sysPermissionService != null ? sysPermissionService.queryByPlatformTypeAndRole(roleCode, platformType) : new ArrayList<>();
            int isThreePowers = 0;
            if (cacheUtils != null) {
                Object cacheValue = cacheUtils.getValueByKey(com.yuanqiao.insight.common.constant.CommonConstant.DATA_DICT_KEY + "insight_threePowers_isEnable");
                if (cacheValue != null) {
                    try {
                        isThreePowers = Integer.parseInt((String) cacheValue);
                    } catch (NumberFormatException e) {
                    }
                }
            }
            if (isThreePowers == 1 && sysRoleService != null && roleCode != null) {
                QueryWrapper<SysRole> roleQueryWrapper = new QueryWrapper<>();
                roleQueryWrapper.eq("role_code", roleCode);
                List<SysRole> roleList = sysRoleService.list(roleQueryWrapper);
                if (CollUtil.isNotEmpty(roleList)) {
                    for (SysRole role : roleList) {
                        if (role != null && !CommonConstant.ADMIN.equals(role.getRoleCode())) {
                            List<SysThreePowerMenu> sysThreePowerMenus;
                            if (SysRoleController.getRoleAuditadm().contains(role.getRoleCode()) || SysRoleController.getRoleSecadm().contains(role.getRoleCode())) {
                                sysThreePowerMenus = sysRoleService.getSysThreepowerMenueByRoleCode(role.getRoleCode());
                                if (sysThreePowerMenus != null && !sysThreePowerMenus.isEmpty()) {
                                    metaList = metaList.stream().filter(p -> p != null && sysThreePowerMenus.stream().anyMatch(tpm -> tpm != null && p.getId() != null && tpm.getPremissionId() != null && p.getId().equals(tpm.getPremissionId()))).collect(Collectors.toList());
                                }
                            } else if (SysRoleController.getRoleRoot().contains(role.getRoleCode())) {
                                LambdaQueryWrapper<SysThreePowerMenu> wrapper = new LambdaQueryWrapper<>();
                                wrapper.ne(SysThreePowerMenu::getRoleCode, "other").eq(SysThreePowerMenu::getShowType, "1");
                                sysThreePowerMenus = sysThreePowerMenuService != null ? sysThreePowerMenuService.list(wrapper) : new ArrayList<>();
                                metaList = metaList.stream().filter(p -> p != null && p.getId() != null && sysThreePowerMenus.stream().noneMatch(tpm -> tpm != null && tpm.getPremissionId() != null && p.getId().equals(tpm.getPremissionId()))).collect(Collectors.toList());
                            } else {
                                LambdaQueryWrapper<SysThreePowerMenu> wrapper = new LambdaQueryWrapper<>();
                                wrapper.eq(SysThreePowerMenu::getShowType, "1");
                                sysThreePowerMenus = sysThreePowerMenuService != null ? sysThreePowerMenuService.list(wrapper) : new ArrayList<>();
                                metaList = metaList.stream().filter(p -> p != null && p.getId() != null && sysThreePowerMenus.stream().noneMatch(tpm -> tpm != null && tpm.getPremissionId() != null && p.getId().equals(tpm.getPremissionId()))).collect(Collectors.toList());
                            }
                        }
                    }
                }
            }
            JSONObject json = new JSONObject();
            JSONArray menujsonArray = new JSONArray();
            this.getPermissionJsonArray(menujsonArray, metaList, null);
            JSONArray authjsonArray = new JSONArray();
            this.getAuthJsonArray(authjsonArray, metaList);
            LambdaQueryWrapper<SysPermission> query = new LambdaQueryWrapper<SysPermission>();
            query.eq(SysPermission::getDelFlag, CommonConstant.DEL_FLAG_0);
            query.eq(SysPermission::getMenuType, CommonConstant.MENU_TYPE_2);
            List<SysPermission> allAuthList = sysPermissionService != null ? sysPermissionService.list(query) : new ArrayList<>();
            JSONArray allauthjsonArray = new JSONArray();
            this.getAllAuthJsonArray(allauthjsonArray, allAuthList);
            json.put("menu", menujsonArray);
            json.put("auth", authjsonArray);
            json.put("allAuth", allauthjsonArray);
            result.setResult(json);
            result.success("查询成功");
        } catch (Exception e) {
            result.error500("查询失败:" + e.getMessage());
            log.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 添加菜单
     *
     * @param permission
     * @return
     */
    @SynMenu
    @AutoLog(value = "菜单管理-新增")
    //@RequiresRoles({ "admin" })
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result<SysPermission> add(@RequestBody SysPermission permission) {
        Result<SysPermission> result = new Result<SysPermission>();
        try {
            if (permission == null) {
                result.error500("参数不能为空");
                return result;
            }
            permission = PermissionDataUtil.intelligentProcessData(permission);
            if (sysPermissionService == null) {
                result.error500("服务不可用");
                return result;
            }
            sysPermissionService.addPermission(permission);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }


    /**
     * 判断一级菜单是否被分配了菜单权限
     *
     * @return
     */
    @RequestMapping(value = "/checkHasMenu", method = RequestMethod.GET)
    public Result<?> checkHasMenu() {
        Result<JSONObject> result = new Result<JSONObject>();
        try {
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            if (oConvertUtils.isEmpty(loginUser)) {
                return Result.error("请登录系统！");
            }
            List<SysPlatformType> platformTypeList = platformTypeService != null ? platformTypeService.list(new QueryWrapper<SysPlatformType>().eq("oam", true).orderByAsc("sort").orderByDesc("create_time")) : new ArrayList<>();
            Map<String, String> platformHasMenuMap = new HashMap<>();
            if (platformTypeList != null) {
                for (SysPlatformType platformType : platformTypeList) {
                    if (platformType != null && platformType.getSubsystemValue() != null) {
                        JSONArray menujsonArray = new JSONArray();
                        List<SysPermission> metaList = sysPermissionService != null ? sysPermissionService.queryByUserAndPlatformType(loginUser.getUsername(), Integer.valueOf(platformType.getSubsystemValue())) : new ArrayList<>();
                        this.getPermissionJsonArray(menujsonArray, metaList, null);
                        String isEmpty = CollectionUtils.isEmpty(menujsonArray) ? "0" : "1";
                        platformHasMenuMap.put("platform_" + platformType.getSubsystemValue(), isEmpty);
                    }
                }
            }
            result.setSuccess(true);
            result.setResult(platformHasMenuMap);
            result.setCode(CommonConstant.SC_OK_200);
            return result;
        } catch (Exception e) {
            result.error500("查询失败:" + e.getMessage());
            log.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 编辑菜单
     *
     * @param permission
     * @return
     */
    @SynMenu
    @AutoLog(value = "菜单管理-编辑")
    //@RequiresRoles({ "admin" })
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<SysPermission> edit(@RequestBody SysPermission permission) {
        Result<SysPermission> result = new Result<>();
        try {
            if (permission == null) {
                result.error500("参数不能为空");
                return result;
            }
            permission = PermissionDataUtil.intelligentProcessData(permission);
            if (sysPermissionService == null) {
                result.error500("服务不可用");
                return result;
            }
            sysPermissionService.editPermission(permission);
            result.success("修改成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 删除菜单
     *
     * @param id
     * @return
     */
    @SynMenu
    @AutoLog(value = "菜单管理-删除")
    //@RequiresRoles({ "admin" })
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public Result<SysPermission> delete(@RequestParam(name = "id", required = true) String id) {
        Result<SysPermission> result = new Result<>();
        try {
            if (id == null || id.trim().isEmpty()) {
                result.error500("ID不能为空");
                return result;
            }
            if (sysPermissionService == null) {
                result.error500("服务不可用");
                return result;
            }
            sysPermissionService.deletePermission(id);
            result.success("删除成功!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500(e.getMessage());
        }
        return result;
    }

    /**
     * 批量删除菜单
     *
     * @param ids
     * @return
     */
    //@RequiresRoles({ "admin" })
    @SynMenu
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    public Result<SysPermission> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<SysPermission> result = new Result<>();
        try {
            if (ids == null || ids.trim().isEmpty()) {
                result.error500("IDs不能为空");
                return result;
            }
            if (sysPermissionService == null) {
                result.error500("服务不可用");
                return result;
            }
            String[] arr = ids.split(",");
            for (String id : arr) {
                if (oConvertUtils.isNotEmpty(id)) {
                    sysPermissionService.deletePermission(id.trim());
                }
            }
            result.success("删除成功!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500(e.getMessage());
        }
        return result;
    }

    /**
     * 获取全部的权限树
     *
     * @return
     */
    @RequestMapping(value = "/queryTreeList", method = RequestMethod.GET)
    public Result<Map<String, Object>> queryTreeList(String platformType) {
        Result<Map<String, Object>> result = new Result<>();
        List<String> ids = new ArrayList<>();
        try {
            QueryWrapper<SysPermission> query = new QueryWrapper<>();
            query.eq("del_flag", CommonConstant.DEL_FLAG_0);
            if (StringUtils.isNotEmpty(platformType)) {
                try {
                    query.eq("platform_type", Integer.parseInt(platformType));
                } catch (NumberFormatException e) {
                    result.error500("平台类型参数格式错误");
                    return result;
                }
            }
            query.orderByAsc("sort_no");
            List<SysPermission> list = sysPermissionService != null ? sysPermissionService.list(query) : new ArrayList<>();
            if (list != null) {
                for (SysPermission sysPer : list) {
                    if (sysPer != null && sysPer.getId() != null) {
                        ids.add(sysPer.getId());
                    }
                }
            }
            List<TreeModel> treeList = getTreeList(list);
            Map<String, Object> resMap = new HashMap<>();
            resMap.put("treeList", treeList);
            resMap.put("ids", ids);
            result.setResult(resMap);
            result.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("查询失败");
        }
        return result;
    }

    //获得树级结构菜单
    public List<TreeModel> getTreeList(List<SysPermission> list) {
        //拿到菜单的所有数据
        //存储根节点的菜单，即一级菜单
        List<TreeModel> treeList = new ArrayList<>();
        //遍历所有数据，找到根节点菜单
        for (SysPermission permission : list) {
            TreeModel tree = new TreeModel(permission);
            if (StringUtils.isEmpty(tree.getParentId())) {
                //找到根节点菜单的时候，寻找这个根节点菜单下的子节点菜单。
                findChilds(tree, list);
                //添加到根节点的列表中
                treeList.add(tree);
            }
        }
        return treeList;
    }

    private void findChilds(TreeModel root, List<SysPermission> list) {
        List<TreeModel> childlist = new ArrayList<>();
        //遍历所有数据，找到是入参父节点的子节点的数据，然后加到childlist集合中。
        for (SysPermission permission : list) {
            TreeModel tree = new TreeModel(permission);
            if (root.getKey().equals(tree.getParentId()))
                childlist.add(tree);
        }
        //若子节点不存在，那么就不必再遍历子节点中的子节点了 直接返回。
        if (childlist.size() == 0)
            return;
        //设置父节点的子节点列表
        root.setChildren(childlist);
        //若子节点存在，接着递归调用该方法，寻找子节点的子节点。
        for (TreeModel childs : childlist) {
            findChilds(childs, list);
        }
    }

    /**
     * 异步加载数据节点
     *
     * @return
     */
    @RequestMapping(value = "/queryListAsync", method = RequestMethod.GET)
    public Result<List<TreeModel>> queryAsync(@RequestParam(name = "pid", required = false) String parentId) {
        Result<List<TreeModel>> result = new Result<>();
        try {
            if (StringUtils.isEmpty(parentId)){
                return result.error500("参数不能为空");
            }
            List<TreeModel> list = sysPermissionService != null ? sysPermissionService.queryListByParentId(parentId) : new ArrayList<>();
            result.setResult(list);
            result.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("查询失败");
        }
        return result;
    }

    /**
     * 查询角色授权
     *
     * @return
     */
    @RequestMapping(value = "/queryRolePermission", method = RequestMethod.GET)
    public Result<List<String>> queryRolePermission(@RequestParam(name = "roleId", required = true) String roleId) {
        Result<List<String>> result = new Result<>();
        try {
            if (sysRolePermissionService == null) {
                result.error500("服务不可用");
                return result;
            }
            List<SysRolePermission> list = sysRolePermissionService.list(new QueryWrapper<SysRolePermission>().lambda().eq(SysRolePermission::getRoleId, roleId));
            if (list == null) {
                result.setResult(new ArrayList<>());
            } else {
                result.setResult(list.stream()
                        .filter(item -> item != null && item.getPermissionId() != null)
                        .map(item -> String.valueOf(item.getPermissionId()))
                        .collect(Collectors.toList()));
            }
            result.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("查询失败");
        }
        return result;
    }

    /**
     * 保存角色授权
     *
     * @return
     */
    @AutoLog(value = "角色管理授权")
    @RequestMapping(value = "/saveRolePermission", method = RequestMethod.POST)
    //@RequiresRoles({ "admin" })
    public Result<String> saveRolePermission(@RequestBody JSONObject json) {
        long start = System.currentTimeMillis();
        Result<String> result = new Result<>();
        try {
            if (json == null) {
                result.error500("请求数据不能为空");
                return result;
            }
            String roleId = json.getString("roleId");
            String permissionIds = json.getString("permissionIds");
            String lastPermissionIds = json.getString("lastpermissionIds");
            if (sysRolePermissionService == null) {
                result.error500("服务不可用");
                return result;
            }
            sysRolePermissionService.saveRolePermission(roleId, permissionIds, lastPermissionIds);
            result.success("保存成功！");
            log.info("======角色授权成功=====耗时:" + (System.currentTimeMillis() - start) + "毫秒");
        } catch (Exception e) {
            result.error500("授权失败！");
            log.error(e.getMessage(), e);
        }
        return result;
    }

    private void getTreeList(List<SysPermissionTree> treeList, List<SysPermission> metaList, SysPermissionTree temp) {
        for (SysPermission permission : metaList) {
            String tempPid = permission.getParentId();
            SysPermissionTree tree = new SysPermissionTree(permission);
            if (temp == null && oConvertUtils.isEmpty(tempPid)) {
                treeList.add(tree);
                if (!tree.getIsLeaf()) {
                    getTreeList(treeList, metaList, tree);
                }
            } else if (temp != null && tempPid != null && tempPid.equals(temp.getId())) {
                temp.getChildren().add(tree);
                if (!tree.getIsLeaf()) {
                    getTreeList(treeList, metaList, tree);
                }
            }

        }
    }

    private void getTreeModelList(List<TreeModel> treeList, List<SysPermission> metaList, TreeModel temp) {
        for (SysPermission permission : metaList) {
            String tempPid = permission.getParentId();
            TreeModel tree = new TreeModel(permission);
            if (temp == null && oConvertUtils.isEmpty(tempPid)) {
                treeList.add(tree);
                if (!tree.getIsLeaf()) {
                    getTreeModelList(treeList, metaList, tree);
                }
            } else if (temp != null && tempPid != null && tempPid.equals(temp.getKey())) {
                temp.getChildren().add(tree);
                if (!tree.getIsLeaf()) {
                    getTreeModelList(treeList, metaList, tree);
                }
            }

        }
    }

    /**
     * 获取权限JSON数组
     *
     * @param jsonArray
     * @param allList
     */
    private void getAllAuthJsonArray(JSONArray jsonArray, List<SysPermission> allList) {
        JSONObject json = null;
        for (SysPermission permission : allList) {
            json = new JSONObject();
            json.put("action", permission.getPerms());
            json.put("status", permission.getStatus());
            json.put("type", permission.getPermsType());
            json.put("describe", permission.getName());
            jsonArray.add(json);
        }
    }

    /**
     * 获取权限JSON数组
     *
     * @param jsonArray
     * @param metaList
     */
    private void getAuthJsonArray(JSONArray jsonArray, List<SysPermission> metaList) {
        for (SysPermission permission : metaList) {
            if (permission.getMenuType() == null) {
                continue;
            }
            JSONObject json = null;
            if (permission.getMenuType().equals(CommonConstant.MENU_TYPE_2) && CommonConstant.STATUS_1.equals(permission.getStatus())) {
                json = new JSONObject();
                json.put("action", permission.getPerms());
                json.put("type", permission.getPermsType());
                json.put("describe", permission.getName());
                jsonArray.add(json);
            }
        }
    }

    /**
     * 获取菜单JSON数组
     *
     * @param jsonArray
     * @param metaList
     * @param parentJson
     */
    private void getPermissionJsonArray(JSONArray jsonArray, List<SysPermission> metaList, JSONObject parentJson) {
        for (SysPermission permission : metaList) {
            if (permission.getMenuType() == null) {
                continue;
            }
            String tempPid = permission.getParentId();
            JSONObject json = getPermissionJsonObject(permission);
            if (json == null) {
                continue;
            }
            if (parentJson == null && oConvertUtils.isEmpty(tempPid)) {
                jsonArray.add(json);
                if (!permission.isLeaf()) {
                    getPermissionJsonArray(jsonArray, metaList, json);
                }
            } else if (parentJson != null && oConvertUtils.isNotEmpty(tempPid) && tempPid.equals(parentJson.getString("id"))) {
                // 类型( 0：一级菜单 1：子菜单 2：按钮 )
                if (permission.getMenuType().equals(CommonConstant.MENU_TYPE_2)) {
                    JSONObject metaJson = parentJson.getJSONObject("meta");
                    if (metaJson.containsKey("permissionList")) {
                        metaJson.getJSONArray("permissionList").add(json);
                    } else {
                        JSONArray permissionList = new JSONArray();
                        permissionList.add(json);
                        metaJson.put("permissionList", permissionList);
                    }
                    // 类型( 0：一级菜单 1：子菜单 2：按钮 )
                } else if (permission.getMenuType().equals(CommonConstant.MENU_TYPE_1) || permission.getMenuType().equals(CommonConstant.MENU_TYPE_0)) {
                    if (parentJson.containsKey("children")) {
                        parentJson.getJSONArray("children").add(json);
                    } else {
                        JSONArray children = new JSONArray();
                        children.add(json);
                        parentJson.put("children", children);
                    }

                    if (!permission.isLeaf()) {
                        getPermissionJsonArray(jsonArray, metaList, json);
                    }
                }
            }

        }
    }

    /**
     * 根据菜单配置生成路由json
     *
     * @param permission
     * @return
     */
    private JSONObject getPermissionJsonObject(SysPermission permission) {
        JSONObject json = new JSONObject();
        // 类型(0：一级菜单 1：子菜单 2：按钮)
        if (permission.getMenuType().equals(CommonConstant.MENU_TYPE_2)) {
            //json.put("action", permission.getPerms());
            //json.put("type", permission.getPermsType());
            //json.put("describe", permission.getName());
            return null;
        } else if (permission.getMenuType().equals(CommonConstant.MENU_TYPE_0) || permission.getMenuType().equals(CommonConstant.MENU_TYPE_1)) {
            json.put("id", permission.getId());
            if (permission.isRoute()) {
                json.put("route", "1");// 表示生成路由
            } else {
                json.put("route", "0");// 表示不生成路由
            }

            if (isWWWHttpUrl(permission.getUrl())) {
                json.put("path", MD5Util.MD5Encode(permission.getUrl(), "utf-8"));
            } else {
                json.put("path", permission.getUrl());
            }

            // 重要规则：路由name (通过URL生成路由name,路由name供前端开发，页面跳转使用)
            if (oConvertUtils.isNotEmpty(permission.getComponentName())) {
                json.put("name", permission.getComponentName());
            } else {
                json.put("name", urlToRouteName(permission.getUrl()));
            }

            // 是否隐藏路由，默认都是显示的
            if (permission.isHidden()) {
                json.put("hidden", true);
            }
            // 聚合路由
            if (permission.isAlwaysShow()) {
                json.put("alwaysShow", true);
            }
            json.put("component", permission.getComponent());
            JSONObject meta = new JSONObject();
            // 由用户设置是否缓存页面 用布尔值
            if (permission.isKeepAlive()) {
                meta.put("keepAlive", true);
            } else {
                meta.put("keepAlive", false);
            }

            /*update_begin author:wuxianquan date:20190908 for:往菜单信息里添加外链菜单打开方式 */
            //外链菜单打开方式
            if (permission.isInternalOrExternal()) {
                meta.put("internalOrExternal", true);
            } else {
                meta.put("internalOrExternal", false);
            }
            /* update_end author:wuxianquan date:20190908 for: 往菜单信息里添加外链菜单打开方式*/

            meta.put("title", permission.getName());

            //update-begin--Author:scott  Date:20201015 for：路由缓存问题，关闭了tab页时再打开就不刷新 #842
            String component = permission.getComponent();
            if (oConvertUtils.isNotEmpty(permission.getComponentName()) || oConvertUtils.isNotEmpty(component)) {
                meta.put("componentName", oConvertUtils.getString(permission.getComponentName(), component.substring(component.lastIndexOf('/') + 1)));
            }
            //update-end--Author:scott  Date:20201015 for：路由缓存问题，关闭了tab页时再打开就不刷新 #842

            if (oConvertUtils.isEmpty(permission.getParentId())) {
                // 一级菜单跳转地址
                json.put("redirect", permission.getRedirect());
                if (oConvertUtils.isNotEmpty(permission.getIcon())) {
                    meta.put("icon", permission.getIcon());
                }
            } else {
                if (oConvertUtils.isNotEmpty(permission.getIcon())) {
                    meta.put("icon", permission.getIcon());
                }
            }
            if (isWWWHttpUrl(permission.getUrl())) {
                meta.put("url", permission.getUrl());
            }
            json.put("meta", meta);
        }

        return json;
    }

    /**
     * 判断是否外网URL 例如： http://localhost:8080/jeecg-boot/swagger-ui.html#/ 支持特殊格式： {{
     * window._CONFIG['domianURL'] }}/druid/ {{ JS代码片段 }}，前台解析会自动执行JS代码片段
     *
     * @return
     */
    private boolean isWWWHttpUrl(String url) {
        if (url != null && (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("{{"))) {
            return true;
        }
        return false;
    }

    /**
     * 通过URL生成路由name（去掉URL前缀斜杠，替换内容中的斜杠‘/’为-） 举例： URL = /isystem/role RouteName =
     * isystem-role
     *
     * @return
     */
    private String urlToRouteName(String url) {
        if (oConvertUtils.isNotEmpty(url)) {
            if (url.startsWith("/")) {
                url = url.substring(1);
            }
            url = url.replace("/", "-");

            // 特殊标记
            url = url.replace(":", "@");
            return url;
        } else {
            return null;
        }
    }

    /**
     * 根据菜单id来获取其对应的权限数据
     *
     * @param sysPermissionDataRule
     * @return
     */
    @RequestMapping(value = "/getPermRuleListByPermId", method = RequestMethod.GET)
    public Result<List<SysPermissionDataRule>> getPermRuleListByPermId(SysPermissionDataRule sysPermissionDataRule) {
        List<SysPermissionDataRule> permRuleList = sysPermissionDataRuleService.getPermRuleListByPermId(sysPermissionDataRule.getPermissionId());
        Result<List<SysPermissionDataRule>> result = new Result<>();
        result.setSuccess(true);
        result.setResult(permRuleList);
        return result;
    }

    /**
     * 判断当前登录用户是否具有参数菜单路径、组件的权限
     *
     * @param url
     * @param component
     * @return
     */
    @RequestMapping(value = "/getPermByCondition", method = RequestMethod.GET)
    public Result<?> getPermByCondition(String url, String component) {
        Result<List<String>> result = new Result<>();
        try {
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            if (sysUser == null || sysPermissionService == null) {
                result.setResult(null);
                result.success("查询成功");
                return result;
            }
            List<SysPermission> sysPermissionList = sysPermissionService.queryByUser(sysUser.getUsername());
            if (sysPermissionList != null) {
                if (StringUtils.isNotEmpty(url)) {
                    sysPermissionList = sysPermissionList.stream().filter(p -> StringUtils.isNotEmpty(p.getUrl()) && p.getUrl().equals(url)).collect(Collectors.toList());
                }
                if (StringUtils.isNotEmpty(component)) {
                    sysPermissionList = sysPermissionList.stream().filter(p -> StringUtils.isNotEmpty(p.getComponent()) && p.getComponent().equals(component)).collect(Collectors.toList());
                }
            }

            if (CollUtil.isNotEmpty(sysPermissionList)) {
                SysPermission sysPermission = sysPermissionList.get(0);
                Integer platformType = sysPermission.getPlatformType();
                List<SysPermission> metaList = sysPermissionService.queryByUserAndPlatformType(sysUser.getUsername(), platformType);
                JSONObject json = new JSONObject();
                JSONArray menujsonArray = new JSONArray();
                this.getPermissionJsonArray(menujsonArray, metaList, null);
                JSONArray authjsonArray = new JSONArray();
                this.getAuthJsonArray(authjsonArray, metaList);
                LambdaQueryWrapper<SysPermission> query = new LambdaQueryWrapper<SysPermission>();
                query.eq(SysPermission::getDelFlag, CommonConstant.DEL_FLAG_0);
                query.eq(SysPermission::getMenuType, CommonConstant.MENU_TYPE_2);
                List<SysPermission> allAuthList = sysPermissionService.list(query);
                JSONArray allauthjsonArray = new JSONArray();
                this.getAllAuthJsonArray(allauthjsonArray, allAuthList);
                json.put("menu", menujsonArray);
                json.put("auth", authjsonArray);
                json.put("allAuth", allauthjsonArray);
                json.put("platformType", platformType);
                result.setResult(json);
                result.success("查询成功");
            } else {
                result.setResult(null);
                result.success("查询成功");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 添加菜单权限数据
     *
     * @param sysPermissionDataRule
     * @return
     */
    //@RequiresRoles({ "admin" })
    @RequestMapping(value = "/addPermissionRule", method = RequestMethod.POST)
    public Result<SysPermissionDataRule> addPermissionRule(@RequestBody SysPermissionDataRule sysPermissionDataRule) {
        Result<SysPermissionDataRule> result = new Result<SysPermissionDataRule>();
        try {
            if (sysPermissionDataRule == null) {
                return result.error500("请求参数为空");
            }
            sysPermissionDataRule.setCreateTime(new Date());
            if (sysPermissionDataRuleService != null) {
                sysPermissionDataRuleService.savePermissionDataRule(sysPermissionDataRule);
            }
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    //@RequiresRoles({ "admin" })
    @RequestMapping(value = "/editPermissionRule", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<SysPermissionDataRule> editPermissionRule(@RequestBody SysPermissionDataRule sysPermissionDataRule) {
        Result<SysPermissionDataRule> result = new Result<SysPermissionDataRule>();
        try {
            if (sysPermissionDataRule == null) {
                return result.error500("请求参数为空");
            }
            if (sysPermissionDataRuleService != null) {
                sysPermissionDataRuleService.saveOrUpdate(sysPermissionDataRule);
            }
            result.success("更新成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 删除菜单权限数据
     *
     * @param id
     * @return
     */
    //@RequiresRoles({ "admin" })
    @RequestMapping(value = "/deletePermissionRule", method = RequestMethod.DELETE)
    public Result<SysPermissionDataRule> deletePermissionRule(@RequestParam(name = "id", required = true) String id) {
        Result<SysPermissionDataRule> result = new Result<SysPermissionDataRule>();
        try {
            if (StringUtils.isEmpty(id)){
                return result.error500("ID参数错误");
            }
            if (sysPermissionDataRuleService != null) {
                sysPermissionDataRuleService.deletePermissionDataRule(id);
            }
            result.success("删除成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 查询菜单权限数据
     *
     * @param sysPermissionDataRule
     * @return
     */
    @RequestMapping(value = "/queryPermissionRule", method = RequestMethod.GET)
    public Result<List<SysPermissionDataRule>> queryPermissionRule(SysPermissionDataRule sysPermissionDataRule) {
        Result<List<SysPermissionDataRule>> result = new Result<>();
        try {
            List<SysPermissionDataRule> permRuleList = new ArrayList<>();
            if (sysPermissionDataRule == null) {
                return result.error500("请求参数为空");
            }
            if (sysPermissionDataRuleService != null) {
                permRuleList = sysPermissionDataRuleService.queryPermissionRule(sysPermissionDataRule);
            }

            result.setResult(permRuleList);
            result.success("查询成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 部门权限表
     *
     * @param departId
     * @return
     */
    @RequestMapping(value = "/queryDepartPermission", method = RequestMethod.GET)
    public Result<List<String>> queryDepartPermission(@RequestParam(name = "departId", required = true) String departId) {
        Result<List<String>> result = new Result<>();
        try {
            if (sysDepartPermissionService == null || departId == null) {
                result.setResult(new ArrayList<>());
                result.setSuccess(true);
                return result;
            }
            List<SysDepartPermission> list = sysDepartPermissionService.list(new QueryWrapper<SysDepartPermission>().lambda().eq(SysDepartPermission::getDepartId, departId));
            if (list != null) {
                result.setResult(list.stream().map(sysDepartPermission -> String.valueOf(sysDepartPermission.getPermissionId())).collect(Collectors.toList()));
            } else {
                result.setResult(new ArrayList<>());
            }
            result.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 保存部门授权
     *
     * @return
     */
    @RequestMapping(value = "/saveDepartPermission", method = RequestMethod.POST)
    //@RequiresRoles({ "admin" })
    public Result<String> saveDepartPermission(@RequestBody JSONObject json) {
        long start = System.currentTimeMillis();
        Result<String> result = new Result<>();
        try {
            if (json == null || sysDepartPermissionService == null) {
                result.error500("请求参数为空或服务不可用");
                return result;
            }
            String departId = json.getString("departId");
            String permissionIds = json.getString("permissionIds");
            String lastPermissionIds = json.getString("lastpermissionIds");
            this.sysDepartPermissionService.saveDepartPermission(departId, permissionIds, lastPermissionIds);
            result.success("保存成功！");
            log.info("======部门授权成功=====耗时:" + (System.currentTimeMillis() - start) + "毫秒");
        } catch (Exception e) {
            result.error500("授权失败！");
            log.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     * 获取字典中配置的所有的平台类型，供下拉框数据使用
     *
     * @return
     */
    @AutoLog(value = "菜单管理-平台类型下拉框")
    @ApiOperation(value = "菜单管理-平台类型下拉框", notes = "菜单管理-平台类型下拉框")
    @GetMapping(value = "/platformTypeList")
    public Result<?> platformTypeList(Boolean status, Boolean oam) {
        JSONArray resultArray = new JSONArray();
        QueryWrapper<SysPlatformType> queryWrapper = new QueryWrapper<>();
        if (status != null) {
            queryWrapper.eq("status", status);
        }
        if (oam != null) {
            queryWrapper.eq("oam", oam);
        }
        queryWrapper.orderByAsc("sort").orderByDesc("create_time");
        List<SysPlatformType> platformTypeList = platformTypeService.list(queryWrapper);
        for (SysPlatformType sysPlatformType : platformTypeList) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("title", sysPlatformType.getTitle());
            jsonObject.put("text", sysPlatformType.getTitle());
            jsonObject.put("value", sysPlatformType.getSubsystemValue());
            jsonObject.put("status", sysPlatformType.getStatus());
            jsonObject.put("icon", sysPlatformType.getIcon());
            jsonObject.put("description", sysPlatformType.getDescription());
            resultArray.add(jsonObject);
        }

        return Result.OK(resultArray);
    }

    /**
     * 查询当前用户的菜单信息
     *
     * @return
     */
    @RequestMapping(value = "/queryByUser", method = RequestMethod.GET)
    public Result queryByUser(Integer platformType) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<SysPermission> metaList = new ArrayList<>();
        if (platformType != null) {
            metaList = sysPermissionService.queryByUserAndPlatformType(loginUser.getUsername(), platformType);
        } else {
            metaList = sysPermissionService.queryByUser(loginUser.getUsername());
        }
        List<SysPermissionTree> treeList = getMenuList(metaList, false);
        setPlatformType(treeList);
        return Result.OK(treeList);
    }
}
